#!/bin/bash

echo "========================================"
echo "员工管理系统部署脚本"
echo "========================================"
echo

# 检查Java环境
echo "正在检查Java环境..."
if ! command -v java &> /dev/null; then
    echo "错误: 未找到Java环境，请先安装JDK 8+"
    exit 1
fi
java -version

# 检查Maven环境
echo
echo "正在检查Maven环境..."
if ! command -v mvn &> /dev/null; then
    echo "错误: 未找到Maven环境，请先安装Maven 3.6+"
    exit 1
fi
mvn -version

# 编译项目
echo
echo "正在清理并编译项目..."
mvn clean package
if [ $? -ne 0 ]; then
    echo "错误: 项目编译失败"
    exit 1
fi

# 查找Tomcat目录
echo
echo "正在查找Tomcat安装目录..."
TOMCAT_DIRS=(
    "/usr/local/tomcat"
    "/opt/tomcat"
    "/usr/share/tomcat9"
    "$HOME/apache-tomcat-9.0"
    "$HOME/tomcat9"
)

TOMCAT_DIR=""
for dir in "${TOMCAT_DIRS[@]}"; do
    if [ -d "$dir" ]; then
        TOMCAT_DIR="$dir"
        break
    fi
done

if [ -z "$TOMCAT_DIR" ]; then
    echo "请手动输入Tomcat安装目录:"
    read -r TOMCAT_DIR
fi

if [ ! -d "$TOMCAT_DIR" ]; then
    echo "错误: Tomcat目录不存在: $TOMCAT_DIR"
    exit 1
fi

# 部署到Tomcat
echo
echo "正在部署到Tomcat..."
cp target/web117.war "$TOMCAT_DIR/webapps/"
if [ $? -ne 0 ]; then
    echo "错误: 部署失败"
    exit 1
fi

echo
echo "========================================"
echo "部署成功！"
echo "========================================"
echo
echo "请按照以下步骤启动系统:"
echo "1. 启动Tomcat服务器"
echo "2. 访问: http://localhost:8080/web117/"
echo "3. 使用默认账户登录:"
echo "   用户名: admin"
echo "   密码: admin123"
echo
echo "注意: 请确保MySQL数据库已启动并执行了database/init.sql脚本"
echo

# 询问是否启动Tomcat
read -p "是否现在启动Tomcat? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if [ -f "$TOMCAT_DIR/bin/startup.sh" ]; then
        echo "正在启动Tomcat..."
        "$TOMCAT_DIR/bin/startup.sh"
        echo "Tomcat已启动，请访问: http://localhost:8080/web117/"
    else
        echo "未找到Tomcat启动脚本，请手动启动"
    fi
fi